package com.pengpai.pangucms.utils;

import com.pengpai.pangucms.VO.CategoryVO;
import com.pengpai.pangucms.VO.MenuVO;
import com.pengpai.pangucms.VO.PermissionVO;
import com.pengpai.pangucms.entity.WebCategory;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

public class TreeUtil {

    public static List<MenuVO> toTree(List<MenuVO> treeList, Integer pid) {
        List<MenuVO> retList = new ArrayList<MenuVO>();
        for (MenuVO parent : treeList) {
            if (pid.equals(parent.getPid())) {
                retList.add(findChildren(parent, treeList));
            }
        }
        return retList;
    }
    private static MenuVO findChildren(MenuVO parent, List<MenuVO> treeList) {
        for (MenuVO child : treeList) {
            if (parent.getId().equals(child.getPid())) {
                if (parent.getChildren() == null) {
                    parent.setChildren(new ArrayList<>());
                }
                parent.getChildren().add(findChildren(child, treeList));
            }
        }
        return parent;
    }


    public static List<CategoryVO> webCategoryVoToTree(List<CategoryVO> treeList, Integer pid) {
        List<CategoryVO> retList = new ArrayList<CategoryVO>();
        for (CategoryVO parent : treeList) {
            if (pid.equals(parent.getParentId())) {
                retList.add(findChildren(parent, treeList));
            }
        }
        return retList;
    }
    private static CategoryVO findChildren(CategoryVO parent, List<CategoryVO> treeList) {
        for (CategoryVO child : treeList) {
            if (parent.getId().equals(child.getParentId())) {
                if (parent.getChildren() == null) {
                    parent.setChildren(new ArrayList<>());
                    parent.setLast(false);
                }
                parent.getChildren().add(findChildren(child, treeList));
            }
        }
        return parent;
    }

    public static List<PermissionVO> getChildrens(PermissionVO root, List<PermissionVO> all) {
        List<PermissionVO> children = all.stream().filter(m -> {
            return Objects.equals(m.getPid(), root.getId());
        }).map(
                (m) -> {
                    m.setChildren(getChildrens(m, all));
                    return m;
                }
        ).collect(Collectors.toList());
        return children;
    }

}